package org.hq.service;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.hq.pojo.WebUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {
    //加密密钥
    private static final String SECRET_KEY = "DFabcd8efg5ab4cdef1ghijklmno9pq4r5s3t2uv1w0xyz"; // 密钥
    //加密方式
    private static final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    private static final String tokenuuid="token:";
    @Autowired
    private RedisTemplate<String, Object> redis;
    /**
     *
     *
     * @param user 用户
     * @param time 保存 token 有效时间与秒为单位
     * @return
     */
    public String saveToken(WebUser user, long time) {
        // 签名密钥
        byte[] secretKeyBytes = SECRET_KEY.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes, signatureAlgorithm.getJcaName());
        //三个小时
        long ttlMillis = 60 * 60 * 1000L * 3;
        // 设置JWT的签发时间和过期时间
        Date now = new Date(System.currentTimeMillis());
        // 使用指定的密钥和算法生成JWT
        JwtBuilder jwt = Jwts.builder();
        //设置id
        jwt.setSubject(user.getUserid());
        // 设置签发时间
        jwt.setIssuedAt(now);
        // 设置过期时间
        jwt.setExpiration(new Date(now.getTime() + time));
        // 设置签名密钥和签名算法
        jwt.signWith(secretKeySpec, signatureAlgorithm);
        // 生成JWT字符串
        String token = jwt.compact();
        //保存 token
        user.setToken(token);
        redis.opsForValue().set(tokenuuid+token,user,time,TimeUnit.SECONDS);
        return token;
    }
    public WebUser isToken(String token) {
        return (WebUser) redis.opsForValue().get(tokenuuid+token);
    }
}
